package net.mihome.app.ui;

import android.app.ActivityManager;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import com.loopj.android.http.RequestParams;

import net.mihome.app.AppContext;
import net.mihome.app.AppManager;
import net.mihome.app.R;
import net.mihome.app.adapter.SeachCommunityAdapter;
import net.mihome.app.bean.Building;
import net.mihome.app.bean.Community;
import net.mihome.app.bean.URLs;
import net.mihome.app.bean.net.ResponsePojo;
import net.mihome.app.common.UIHelper;
import net.mihome.app.utils.MiAsyncHttpResponseHandler;
import net.mihome.app.utils.RequestParamsFactory;
import net.mihome.app.widget.LoadingDialog;

import org.apache.http.Header;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * Created by ZHAO on 2015/2/1 0001.
 */
public class SearchCommunityActivity extends BaseActivity {
    SeachCommunityAdapter adapter;
    List<Community> list=new ArrayList<>();
    EditText communityNameEt;
    Button searchBtn;
    ListView listView;
    LoadingDialog loadingDialog;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.seach_community);
        communityNameEt= (EditText) findViewById(R.id.edit_community_name);
        searchBtn= (Button) findViewById(R.id.search);
        listView= (ListView) findViewById(R.id.community_listview);
        adapter=new SeachCommunityAdapter(this,list);
        listView.setAdapter(adapter);
        loadingDialog=new LoadingDialog(this);
        searchBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(communityNameEt.getText()!=null&&!"".equals(communityNameEt.getText().toString())){
                    search(communityNameEt.getText().toString());
                }else{
                    Toast.makeText(SearchCommunityActivity.this,"请输入关键字",Toast.LENGTH_SHORT).show();
                }
            }
        });
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                SeachCommunityAdapter.ViewContaiar viewContaiar= (SeachCommunityAdapter.ViewContaiar) view.getTag();
                if(viewContaiar!=null&&viewContaiar.community!=null){
                    Community community=viewContaiar.community;
//                    updateCommunity(community);
//                    showBuilding(community);
                    showTipDialog(community);
                }else{
                    Toast.makeText(SearchCommunityActivity.this,"该小区无效",Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
    public void back(View view){
        finish();
    }
    /**
     * 通过接口查询小区
     * */
    public void search(String name){
        if(!loadingDialog.isShowing()){
            loadingDialog.show();
        }
        RequestParams requestParams= RequestParamsFactory.newInstance(AppContext.getInstance());
        requestParams.add("name",name);
        AppContext.ASYNC_HTTP_CLIENT.get(this, URLs.MIHOME_GET_COMMINUTY_SEARCH,requestParams,new MiAsyncHttpResponseHandler<List<Map>>() {
            @Override
            public void onSuccess(int arg0, Header[] arg1, ResponsePojo<List<Map>> responsePojo) {
                list.clear();
                List<Community> communityList=Community.parseList(responsePojo.getData());
                if(communityList!=null&&!communityList.isEmpty()){
                    list.addAll(communityList);
                }
                adapter.notifyDataSetChanged();
                loadingDialog.dismiss();
            }

            @Override
            public void onFailure(int arg0, Header[] arg1, Throwable arg3) {
                Toast.makeText(SearchCommunityActivity.this,arg3.getMessage(),Toast.LENGTH_SHORT).show();
                loadingDialog.dismiss();
            }
        });
    }
    /**
     * 获取到小区里边的楼宇，让用户选择
     * */
    public void showBuilding(Community community){
        if(!loadingDialog.isShowing()){
            loadingDialog.show();
        }
        RequestParams requestParams=RequestParamsFactory.newInstance(AppContext.getInstance());
        requestParams.put("want_community_id", community.getId() + "");
        AppContext.ASYNC_HTTP_CLIENT.get(this,URLs.MIHOME_GET_COMMINUTY_GETBUILDING,requestParams,new MiAsyncHttpResponseHandler<List<Map>>() {
            @Override
            public void onSuccess(int arg0, Header[] arg1, ResponsePojo<List<Map>> responsePojo) {
                List<Building> buildingList=Building.parseList(responsePojo.getData());
                if(buildingList!=null&&!buildingList.isEmpty()){
                    if(loadingDialog.isShowing()){
                        loadingDialog.dismiss();
                    }
                    showBuildDialog(buildingList);
                }else{
                    Toast.makeText(SearchCommunityActivity.this,"该小区还没有设置建筑可供选择",Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(int arg0, Header[] arg1, Throwable arg3) {
                Toast.makeText(SearchCommunityActivity.this,arg3.getMessage(),Toast.LENGTH_SHORT).show();
            }
        });
    }
    /**
     * 弹出楼栋选择创偶
     * */
    public void showBuildDialog(final List<Building> buildings){
        Iterator<Building> iterator=buildings.iterator();
        String[] names=new String[buildings.size()];
        for(int i=0;i<buildings.size();i++){
            names[i]=buildings.get(i).getName();
        }
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setIcon(R.drawable.ic_launcher);
        builder.setTitle("请选择楼号");
        final ChioceItem chioceItem=new ChioceItem();
        chioceItem.setI(0);
        builder.setSingleChoiceItems(names, chioceItem.getI(), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                chioceItem.setI(which);
            }
        });
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                Building building=buildings.get(chioceItem.getI());
                Toast.makeText(SearchCommunityActivity.this,building.getName(),Toast.LENGTH_SHORT).show();
                updateCommunity(building);
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
                if(loadingDialog.isShowing()){
                    dialog.dismiss();
                }
            }
        });
        builder.create().show();
    }
    public void showTipDialog(final Community community){
        AlertDialog.Builder builder=new AlertDialog.Builder(this);
        builder.setTitle("确认");
        builder.setMessage("是否确定要切换到"+community.getName()+"?");
        builder.setNegativeButton("取消",new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                dialogInterface.dismiss();
            }
        });
        builder.setPositiveButton("确定",new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                updateCommunity(community);
                dialogInterface.dismiss();
            }
        });
        builder.show();
    }
    /**
     * 设置小区(根据楼栋设置)
     * */

    public void updateCommunity(Building building){
        if(!loadingDialog.isShowing()){
            loadingDialog.show();
        }
        RequestParams requestParams=RequestParamsFactory.newInstance(AppContext.getInstance());
        requestParams.add("building_id",building.getId()+"");
        AppContext.ASYNC_HTTP_CLIENT.get(this,URLs.MIHOME_GET_COMMINUTY_UPDATE,requestParams,new MiAsyncHttpResponseHandler<Map>() {
            @Override
            public void onSuccess(int arg0, Header[] arg1, ResponsePojo<Map> responsePojo) {
                Toast.makeText(SearchCommunityActivity.this,"设置成功",Toast.LENGTH_SHORT).show();
                loadingDialog.dismiss();
                showLogout();
            }

            @Override
            public void onFailure(int arg0, Header[] arg1, Throwable arg3) {
                Toast.makeText(SearchCommunityActivity.this,arg3.getMessage(),Toast.LENGTH_SHORT).show();
                loadingDialog.dismiss();
            }
        });
    }
    /**
     * 设置小区(根据小区设置)
     * */

    public void updateCommunity(Community community){
        if(!loadingDialog.isShowing()){
            loadingDialog.show();
        }
        RequestParams requestParams=RequestParamsFactory.newInstance(AppContext.getInstance());
        requestParams.add("new_community_id",community.getId()+"");
        AppContext.ASYNC_HTTP_CLIENT.get(this,URLs.MIHOME_GET_COMMINUTY_UPDATE,requestParams,new MiAsyncHttpResponseHandler<Map>() {
            @Override
            public void onSuccess(int arg0, Header[] arg1, ResponsePojo<Map> responsePojo) {
                Toast.makeText(SearchCommunityActivity.this,"设置成功",Toast.LENGTH_SHORT).show();
                loadingDialog.dismiss();
                showLogout();
            }

            @Override
            public void onFailure(int arg0, Header[] arg1, Throwable arg3) {
                Toast.makeText(SearchCommunityActivity.this,arg3.getMessage(),Toast.LENGTH_SHORT).show();
                loadingDialog.dismiss();
            }
        });
    }
    /**
     * 修改成功后，提示用户重新登录
     * */

    public void showLogout(){
        AlertDialog.Builder builder=new AlertDialog.Builder(this);
        builder.setTitle("提示");
        builder.setMessage("切换小区之后，请重新登录生效.");
        builder.setPositiveButton("确定",new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                UIHelper.loginOrLogout(SearchCommunityActivity.this);
                AppManager.getAppManager().finishActivity(MainPager.class);
            }
        });
        builder.setCancelable(false);
        builder.show();
    }
}

class ChioceItem{
    private int i;

    public int getI() {
        return i;
    }

    public void setI(int i) {
        this.i = i;
    }
}